package com.siyoumi.app.sys.service.wx_center.common_handle;

import com.siyoumi.app.sys.service.wx_center.CenterHandler;
import com.siyoumi.app.sys.service.wx_center.CenterHandlerContext;
import com.siyoumi.app.sys.service.wx_center.CenterHandlerData;
import com.siyoumi.app.sys.service.wx_center.ICenterHandle;
import com.siyoumi.component.LogPipeLine;
import com.siyoumi.component.http.InputData;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;

//企业微信，公众号解密xml
@Slf4j
public class CenterHandleDecXmlAndCheckSign
        implements ICenterHandle {
    @Override
    public XReturn handle(CenterHandlerContext ctx) {
        LogPipeLine.of().setLogMsg("CenterHandleCropDecXmlAndCheckSign");

        CenterHandlerData data = ctx.getHandleData();

        //企业微信需要对内容进行解密
        String xmlEncrypt = data.getInMsg().getData("Encrypt");
        log.debug("xml_encrypt: {}", xmlEncrypt);

        //检查签名
        checkSign(xmlEncrypt, ctx.getEntityConfig().getKey());

        //解密xml
        String xmlStr = CenterHandler.getInstance(data.getX()).decryptTxt(xmlEncrypt);
        LogPipeLine.of().setLogMsgFormat("xml: {0}", xmlStr);

        //替换真正的xml内容
        ctx.setHandleData(CenterHandlerData.getInstance(xmlStr, data.getX()));

        //ctx.setFinal();
        return null;
    }


    static public void checkSign(String xmlEncrypt, String x) {
        InputData inputData = InputData.fromRequest();

        String timestamp = inputData.input("timestamp");
        String nonce = inputData.input("nonce");
        String signature = inputData.input("msg_signature");

        if (XStr.isNullOrEmpty(timestamp)
                || XStr.isNullOrEmpty(nonce)
                || XStr.isNullOrEmpty(signature)) {
            XValidator.err(50061, "缺少签名参数");
        }

        SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfig(x, true);
        String token = entityConfig.getAconfig_token();

        String[] ss = new String[]{token, timestamp, nonce, xmlEncrypt};
        String str1_sign = CenterHandler.getSign(ss);

        if (!str1_sign.equals(signature)) {
            String errmsg = "签名失败 , " + str1_sign + " != " + signature;
            XValidator.err(50069, errmsg);
        }
    }
}
